clear all
set more off
set mem 10000000
set matsize 10000
version 12

************************************************** 
*** Build File to Construct Land Gradient Data ***
************************************************** 

** Set file paths
do "$path_code/paths.do"

********************************************************************************
********************************************************************************

** INSHEET ALL FILES, CONVERT TO STATA FORMAT
cd "$path/data/other spatial data/SRTM-elevation/raw xls"

local counter = 0

local files: dir . files "*elevation.xls"
foreach file in `files' {
  local counter = `counter' + 1
  import excel "`file'", clear
  
  keep B F G I
  
  rename B c_code01
  rename F grad_min
  rename G grad_max
  rename I grad_mean
  drop if c_code01 == "C_CODE01" | c_code01 == "c_code01" | c_code01 == "" | c_code01 == "Pandaul"
  drop if strpos(c_code01, " ")
  
   
  gen st_code = substr(c_code01,1,2)
  gen dt_code = substr(c_code01,3,2)
  gen bk_code = substr(c_code01,5,4)
  gen vi_code = substr(c_code01,9,8)
  drop if st_code == ""
  destring st_code dt_code bk_code vi_code grad*, replace
  save "$path/data/other spatial data/SRTM-elevation/elevation stata/elev_`counter'_prelim.dta", replace

}

cd "$path/data/other spatial data/SRTM-elevation/raw xls"

local counter = 1
local extrafiles: dir . files "*extra.xls"
foreach file in `extrafiles' {
  local counter = `counter' + 1
  import excel "`file'", clear firstrow
  
  rename *, lower
  keep *c_code01 rastervalu
  
  drop zstats*
  cap rename *c_code01 c_code01
  rename rastervalu gradient

  drop if c_code01 == ""

  
  gen grad_min = gradient
  gen grad_max = gradient
  gen grad_mean = gradient
  drop gradient
  
  gen st_code = substr(c_code01,1,2)
  drop if st_code == ""
  gen dt_code = substr(c_code01,3,2)
  gen bk_code = substr(c_code01,5,4)
  gen vi_code = substr(c_code01,9,8)
  cap destring grad*, replace
  destring st_code dt_code bk_code vi_code, replace
  
  save "$path/data/other spatial data/SRTM-elevation/elevation stata/elev_extra_`counter'_prelim.dta", replace

  }

cd "$path/data/other spatial data/SRTM-elevation/elevation stata"
  
local stata_files: dir . files "*prelim.dta"

use "elev_1_prelim.dta", clear
foreach file in `stata_files' {
    di "`file'"
    append using "`file'"
}
duplicates drop st_code dt_code vi_code, force

replace grad_min = . if grad_min == -9999
replace grad_max = . if grad_max == -9999
replace grad_mean = . if grad_mean == -9999

save "$path/data/village gis maps/elev_stata_all.dta", replace

********************************************************************************
********************************************************************************
